import cloud from '@lafjs/cloud'
let data
let dbName = 'admin-teachers'
const db = cloud.mongo.db
import { pinyin } from "pinyin-pro";

export default async function (ctx: FunctionContext) {
  data = ctx.body.data

  switch (ctx.body.type) {
    case "add"://新增
      return await add()
      break;
    case "update"://修改
      return await cloud.utils.updateData(dbName, data)
      break;
    case "del"://删除
      return await cloud.utils.deleteData(dbName, data)
      break;
    case "options"://字典
      return await optionsFunc()
      break;
    case "list"://分页
      return await list()
      break;
    case "query"://不分页
      return await query()
      break;
    case "detail"://详情
      return await detail()
      break;
    case "longest"://最长
      return await longestTeachingProgram()
      break;
    case "occupation"://职业最长
      return await occupation()
      break;
    case "importExcel"://导入excel
      return await importExcel()
      break;
    default:
      break;
  }

  async function add() {
    await cloud.utils.addData(dbName, data)
    await setPinyin()
    return cloud.utils.requestReturn({ data: "" })
  }

  //设置pinyin字段
  async function setPinyin() {
    let fieldJson = { teachingDirection: 1, lecturerName: 1, teachingType: 1 }
    let aa = await db.collection(dbName).find({ teachingDirection_pinyin: { $exists: false } }).project(fieldJson).toArray()
    let bb = await db.collection(dbName).find({ lecturerName_pinyin: { $exists: false } }).project(fieldJson).toArray()
    let cc = await db.collection(dbName).find({ teachingType_pinyin: { $exists: false } }).project(fieldJson).toArray()

    let array = [...aa, ...bb, ...cc]

    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      await cloud.utils.updateData(dbName, {
        teachingDirection_pinyin: pinyin(element.teachingDirection, { toneType: "none" }),//授课方向拼音
        lecturerName_pinyin: pinyin(element.lecturerName, { toneType: "none" }),//讲师姓名拼音
        _id: element._id
      })
    }
  }

  async function query() {
    let aa = await db.collection(dbName).find({}).toArray()
    return cloud.utils.requestReturn({ data: aa })
  }

  async function importExcel() {
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      element.source = "file"
      await cloud.nw.db.add({
        dbName: dbName,
        dataJson: element,
        cancelAddTime: false,
      });
    }
    return cloud.utils.requestReturn({ data: "success" })
  }

  async function detail() {
    let res = await cloud.nw.db.findByWhereJson({
      dbName,
      whereJson: { _id: data._id },
    });
    return cloud.utils.requestReturn({ data: res })
  }

  async function occupation() {
    const db = cloud.database();
    const fieldName = 'position'; // 替换为要查询的字段名称

    const result = await db.collection(dbName)
      .aggregate()
      .project({
        [fieldName]: 1,
        length: { $strLenCP: `$${fieldName}` } // 计算字段内容的长度
      })
      .sort({ length: -1 }) // 按长度降序排序
      .limit(1) // 只取最长的那一条
      .end();
    return cloud.utils.requestReturn({ data: result })
  }

  async function longestTeachingProgram() {
    const db = cloud.database();
    const fieldName = 'teachingProgram'; // 替换为要查询的字段名称

    const result = await db.collection(dbName)
      .aggregate()
      .project({
        [fieldName]: 1,
        length: { $strLenCP: `$${fieldName}` } // 计算字段内容的长度
      })
      .sort({ length: -1 }) // 按长度降序排序
      .limit(1) // 只取最长的那一条
      .end();
    return cloud.utils.requestReturn({ data: result })
  }

  async function optionsFunc() {
    let array = await db.collection(dbName).find({}).toArray()
    let arr = []
    array.forEach(element => {
      if (element[data.key]) arr.push(element[data.key])
    });
    return cloud.utils.requestReturn({ data: cloud.utils.unique(arr) })
  }

  async function list() {
    //setPinyin()
    let whereJson = cloud.utils.fuzzyQuery({ ...data })

    let res = await cloud.nw.db.select({
      dbName,
      getCount: true,
      pageIndex: data.pageIndex,
      pageSize: data.pageSize,
      // 主表 where 条件
      whereJson,
      // 主表排序规则
      sortArr: [
        { "name": "teachingDirection_pinyin", 'type': "asc" },
        { "name": "lecturerName_pinyin", 'type': "asc" },
        { "name": "teachingType_pinyin", 'type': "asc" },
        { "name": "_add_time", "type": "desc" }]
    });
    return cloud.utils.requestReturn({ data: res })
  }
}
